"""
安居客房价查询
-涉及区域: 浦口区
"""
url = "https://nanjing.anjuke.com/sale/pukou/m12939-p{}/"

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException, TimeoutException

class AnjukeHousePrice:
    def __init__(self, ):
        self.options = webdriver.EdgeOptions()
        # self.options.add_argument("--headless")
        self.options.add_experimental_option("excludeSwitches", ["enable-automation"])
        self.options.add_experimental_option("useAutomationExtension", False)

        self.driver = webdriver.Edge(options=self.options)
        self.driver.implicitly_wait(10)
        self.driver.maximize_window()

        self.elements = None

    def get_elements(self,page_number):
        """
        获取房源信息列表
        :return:
        """
        try:
            self.driver.get(url.format(page_number))
            self.elements = self.driver.find_elements(By.CLASS_NAME, "property")
        except TimeoutException:
            print("页面加载超时，请检查网络连接或页面是否存在。")
            return None
        return self.elements

    def get_element_count(self):
        """
        获取房源信息数量
        :return:
        """
        if self.elements is None:
            print("请先调用get_elements方法获取房源信息列表。")
            return 0
        return len(self.elements)

    def get_house_info(self):
        """
        获取房源信息
        :return:
        """
        if self.elements is None:
            print("请先调用get_elements方法获取房源信息列表。")
            return []

        house_list = []
        for element in self.elements:
            try:
                detail = {}
                # 房源标题信息
                tittle_element = element.find_element(By.CLASS_NAME, "property-content-title").find_element(By.TAG_NAME, "h3")
                detail["title"] = tittle_element.text
                # 小区名
                community_name = element.find_element(By.CLASS_NAME,"property-content-info-comm-name").text
                detail["community_name"] = community_name
                # 总价
                total_price = element.find_element(By.CLASS_NAME, "property-price-total-num").text
                detail["total_price"] = total_price
                # 均价
                avg_price = element.find_element(By.CLASS_NAME, "property-price-average").text
                detail["avg_price"] = avg_price
                # 房源信息
                content_info = element.find_element(By.CLASS_NAME, "property-content-info").find_elements(By.TAG_NAME,"p")
                if len(content_info) == 5:
                    # 类型
                    detail["house_type"] = content_info[0].text
                    # 面积
                    detail["house_area"] = content_info[1].text
                    # 楼高
                    detail["house_floor"] = content_info[3].text
                    # 朝向
                    detail["house_towards"] = content_info[2].text
                    # 年代
                    detail["house_year"] = content_info[4].text
                # 地址
                address = element.find_element(By.CLASS_NAME, "property-content-info-comm-address").text
                detail["address"] = address

                # 房源链接
                house_link = element.find_element(By.TAG_NAME, "a").get_attribute("href")
                detail["house_link"] = house_link

                house_list.append(detail)
            except NoSuchElementException:
                print("某些元素未找到，可能是页面结构变化或元素不存在。")
                continue

        return house_list


    def get_house_detail(self, page_number):
        """
        获取房源信息
        :return:
        """
        house_list = []
        for i in range(1, page_number):
            self.driver.get(url.format(i))
            elements = self.driver.find_elements(By.CLASS_NAME,"property")
            for element in elements:
                try:
                    detail = {}
                    # 房源标题信息
                    tittle_element = element.find_element(By.CLASS_NAME, "property-content-title").find_element(By.TAG_NAME, "h3")
                    detail["title"] = tittle_element.text
                    # 小区名
                    community_name = element.find_element(By.CLASS_NAME,"property-content-info-comm-name").text
                    detail["community_name"] = community_name
                    # 总价
                    total_price = element.find_element(By.CLASS_NAME, "property-price-total-num").text
                    detail["total_price"] = total_price
                    # 均价
                    avg_price = element.find_element(By.CLASS_NAME, "property-price-average").text
                    detail["avg_price"] = avg_price
                    # 房源信息
                    content_info = element.find_element(By.CLASS_NAME, "property-content-info").find_elements(By.TAG_NAME,"p")
                    if len(content_info) == 5:
                        # 类型
                        detail["house_type"] = content_info[0].text
                        # 面积
                        detail["house_area"] = content_info[1].text
                        # 楼高
                        detail["house_floor"] = content_info[3].text
                        # 朝向
                        detail["house_towards"] = content_info[2].text
                        # 年代
                        detail["house_year"] = content_info[4].text
                    # 地址
                    address = element.find_element(By.CLASS_NAME, "property-content-info-comm-address").text
                    detail["address"] = address

                    # 房源链接
                    house_link = element.find_element(By.TAG_NAME, "a").get_attribute("href")
                    detail["house_link"] = house_link
                    house_list.append(detail)
                except NoSuchElementException:
                    print(f"Page {i}: No house information found.")
                    continue
        return house_list

    def close(self):
        self.driver.quit()

if __name__ == "__main__":
    link = "https://nanjing.anjuke.com/sale/pukou/m12939-p1/"

    page_num = 2
    anjuke = AnjukeHousePrice()
    house_detail = anjuke.get_house_detail(page_num)
    # print(house_detail)
    anjuke.close()

